(({config,server,helper,components,CONST} = vinculum)=>{
  let r = React;
  let rd = ReactDOM;
  let query_app = config.query.app || 'application';
  let query_fun = config.query.fun || 'main';
	let actionName = {
		login:CONST.TABLE_PREFIX + '_login'
	};
	components.setTheme('bootstrap');
	//components.setTheme('amazeui');
	
	function gFunDel(checks){
    let actionName = CONST.TABLE_PREFIX + '_' + query_app + '_delete';
		if(confirm('确认删除？')){
      server.invokeAction(actionName,{
        id:checks[0].id
      }).then(function(result){
          alert('删除成功！');
					location = config.appname + '?app=' + query_app;
      })['catch'](server.catchFun);
		}
  }
	
	function gFunLinkResource(cks){
		let arrroles = [];
		for(let i1=0,len=cks.length;i1<len;i1++){
			arrroles.push(cks[i1].id);
		}
		let p2 = {
			appid:config.query.id
			,resourceids:arrroles.join(',')
		};
		let actionName = CONST.TABLE_PREFIX + '_appandresource_update';
		server.invokeAction(actionName,p2).then(function(result){
			alert(result);
			location = config.appname + '?app=' + query_app;
		})['catch'](server.catchFun);
	}
	
	function gFunUserRoleResource(cks){
		let arrroles = [];
		for(let i1=0,len=cks.length;i1<len;i1++){
			arrroles.push(cks[i1].id);
		}
		let p2 = {
			userid:config.query.id
			,roleids:arrroles.join(',')
		};
		let actionName = CONST.TABLE_PREFIX + '_user_role_update';
		server.invokeAction(actionName,p2).then(function(result){
			alert(result);
			location = config.appname + '?app=' + query_app;
		})['catch'](server.catchFun);
	}
	
	function gFunLinkRole(cks){
		let arrroles = [];
		for(let i1=0,len=cks.length;i1<len;i1++){
			arrroles.push(cks[i1].id);
		}
		let p2 = {
			whatid:config.query.id
			,whattype:query_app
			,roleids:arrroles.join(',')
		};
		let actionName = CONST.TABLE_PREFIX + '_authorization_update';
		server.invokeAction(actionName,p2).then(function(result){
			alert(result);
			location = config.appname + '?app=' + query_app;
		})['catch'](server.catchFun);
	}
	
	let isornotOption = [
    {value:'0',name:'否'}
    ,{value:'1',name:'是'}
  ];  
  let sourceFileTypeOption = [
    {value:'css',name:'css'}
    ,{value:'js',name:'js'}
  ];  
	let sourceTypeOption = [
    {value:'0',name:'链接'}
    ,{value:'1',name:'本地'}
    ,{value:'2',name:'CDN'}
  ];
  let isfilterOption = [
    {value:CONST.FILTER_TYPES.NONE,name:'否'}
    ,{value:CONST.FILTER_TYPES.ROLE,name:'角色过滤'}
    ,{value:CONST.FILTER_TYPES.ROOT,name:'系统管理员过滤'}
    ,{value:CONST.FILTER_TYPES.USER,name:'登陆用户过滤'}
    ,{value:CONST.FILTER_TYPES.APP,name:'第三方过滤'}
  ]
  
  let templateOption = [
    {value:'empty',name:'empty'}
  ];
  
  let serviceTypeOption = [
    {value:CONST.SERVICE_TYPES.SELECT,name:'查询'}
    ,{value:CONST.SERVICE_TYPES.INSERT,name:'新增'}
    ,{value:CONST.SERVICE_TYPES.UPDATE,name:'修改'}
    ,{value:CONST.SERVICE_TYPES.DELETE,name:'删除'}
  ];
  
  let lockTypeOption = [
    {value:'',name:''}
    ,{value:'action',name:'action'}
    ,{value:'action_param',name:'action_param'}
  ];
  
  let dataSourceOption = [
    {value:'systemdb',name:'系统数据库'}
  ];
	
	function gFunOpenApp(checks){
		let id = checks[0].id;
		let url = config.baseUrl + 'application/' + id;
    window.open(url);
  }
  
  function gFunOpenService(checks){
    window.open(config.baseUrl + 'service/' + checks[0].id);
  }
  
  function gFunOpenAction(checks){
    window.open(config.baseUrl + 'action/' + checks[0].id);
  }
	
	let constGridHeaders = {
		application:[
			{key:'name',name:'名称'}
			,{key:'title',name:'标题'}
			,{key:'isfilter',name:'是否过滤'}
			,{key:'islog',name:'是否记录日志'}
			,{key:'debug',name:'是否调试'}
			,{key:'disabled',name:'是否禁用'}
			,{key:'createtime',name:'创建时间'}
		]
		,action:[
			{key:'name',name:'名称'}
			,{key:'l10n',name:'标题'}
			,{key:'locktype',name:'锁类型'}
			,{key:'isfilter',name:'是否过滤'}
			,{key:'disabled',name:'是否禁用'}
			,{key:'islog',name:'是否记录日志'}
			,{key:'createtime',name:'创建时间'}
		]
		,service:[
			{key:'name',name:'名称'}
			,{key:'l10n',name:'标题'}
			,{key:'type',name:'类型'}
			,{key:'datasourceid',name:'数据源'}
			,{key:'isfilter',name:'是否过滤'}
			,{key:'disabled',name:'是否禁用'}
			,{key:'islog',name:'是否记录日志'}
			,{key:'createtime',name:'创建时间'}
		]
		,resource:[
			{key:'name',name:'资源名称'}
			,{key:'version',name:'版本'}
			,{key:'type',name:'main类型'}
			,{key:'filetype',name:'资源类型'}
			,{key:'main',name:'资源类型'}
			,{key:'ordernum',name:'排序'}
		]
		,role:[
			{key:'name',name:'名称'}
			,{key:'l10n',name:'描述'}
		]
		,user:[
			{key:'username',name:'用户名'}
			,{key:'createtime',name:'创建时间'}
		]
	};
	
	let constGridOperations = {
		application:[
			{name:'打开',needCheck:true,onClick:gFunOpenApp}
			,{name:'新增',theme:'primary',href:config.appname + '?app=application&fun=insert'}
			,{name:'修改',theme:'warning',href:config.appname + '?app=application&fun=update',needCheck:true}
			,{name:'复制',theme:'info',href:config.appname + '?app=application&fun=copy',needCheck:true}
			,{name:'删除',theme:'danger',needCheck:true,onClick:gFunDel}
			,{name:'权限',theme:'info',href:config.appname + '?app=application&fun=auth',needCheck:true}
			,{name:'资源',theme:'success',href:config.appname + '?app=application&fun=resource',needCheck:true}
			,{name:'HTML',theme:'primary',href:config.appname + '?app=application&fun=edit&edittype=html',needCheck:true}
			,{name:'JS',theme:'warning',href:config.appname + '?app=application&fun=edit&edittype=js',needCheck:true}
			,{name:'CSS',theme:'success',href:config.appname + '?app=application&fun=edit&edittype=css',needCheck:true}
		]
		,service:[
        {name:'打开',needCheck:true,onClick:gFunOpenService}
        ,{name:'新增',theme:'primary',href:config.appname + '?app=service&fun=insert'}
        ,{name:'修改',theme:'warning',href:config.appname + '?app=service&fun=update',needCheck:true}
			,{name:'复制',theme:'info',href:config.appname + '?app=service&fun=copy',needCheck:true}
        ,{name:'删除',theme:'danger',needCheck:true,onClick:gFunDel}
        ,{name:'权限',theme:'info',href:config.appname + '?app=service&fun=auth',needCheck:true}
      ]
			,action:[
        {name:'打开',needCheck:true,onClick:gFunOpenAction}
        ,{name:'新增',theme:'primary',href:config.appname + '?app=action&fun=insert'}
        ,{name:'修改',theme:'warning',href:config.appname + '?app=action&fun=update',needCheck:true}
			,{name:'复制',theme:'info',href:config.appname + '?app=action&fun=copy',needCheck:true}
        ,{name:'删除',theme:'danger',needCheck:true,onClick:gFunDel}
        ,{name:'权限',theme:'info',href:config.appname + '?app=action&fun=auth',needCheck:true}
      ]
			,user:[
        {name:'新增',theme:'primary',href:config.appname + '?app=user&fun=insert'}
        ,{name:'修改',theme:'warning',href:config.appname + '?app=user&fun=update',needCheck:true}
        ,{name:'删除',theme:'danger',needCheck:true,onClick:gFunDel}
        ,{name:'关联角色',theme:'info',href:config.appname + '?app=user&fun=user_role',needCheck:true}
      ]
			,role:[
        {name:'新增',theme:'primary',href:config.appname + '?app=role&fun=insert'}
        ,{name:'修改',theme:'warning',href:config.appname + '?app=role&fun=update',needCheck:true}
        ,{name:'删除',theme:'danger',needCheck:true,onClick:gFunDel}
      ]
			,resource:[
        {name:'新增',theme:'primary',href:config.appname + '?app=resource&fun=insert'}
        ,{name:'修改',theme:'warning',href:config.appname + '?app=resource&fun=update',needCheck:true}
			,{name:'复制',theme:'info',href:config.appname + '?app=resource&fun=copy',needCheck:true}
        ,{name:'删除',theme:'danger',needCheck:true,onClick:gFunDel}
      ]
	};
	
	let constCopyItems = {
		application:[
			{name:'name',show:'新应用名称'}
		]
		,service:[
			{name:'name',show:'新服务名称'}
		]
		,action:[
			{name:'name',show:'新动作名称'}
		]
		,resource:[
			{name:'name',show:'资源名称'}
			,{name:'version',show:'版本'}
			,{name:'type',show:'链接类型',type:'select',items:sourceTypeOption}
			,{name:'filetype',show:'资源类型',type:'select',items:sourceFileTypeOption}
			,{name:'main',show:'文件内容',type:'ace'}
			,{name:'ordernum',show:'排序'}
		]
	};

	let constInsertItems = {
		application:[
			{name:'name',show:'应用名称'}
			,{name:'title',show:'应用标题'}
			,{name:'description',show:'应用描述',type:'textarea'}
			,{name:'keywords',show:'应用关键字'}
			,{name:'authurl',show:'授权地址'}
			,{name:'viewport',show:'页面视图'}
			,{name:'before_service',show:'执行服务'}
			,{name:'before_action',show:'执行动作'}
			,{name:'isfilter',show:'是否过滤',type:'select',items:isfilterOption}
			,{name:'islog',show:'是否记录日志',type:'select',items:isornotOption}
			,{name:'debug',show:'是否调试',type:'select',items:isornotOption}
			,{name:'disabled',show:'是否禁用',type:'select',items:isornotOption}
		]
		,service:[
			{name:'name',show:'名称'}
			,{name:'l10n',show:'描述'}
			,{name:'type',show:'类型',type:'select',items:serviceTypeOption}
			,{name:'isfilter',show:'是否过滤',type:'select',items:isfilterOption}
			,{name:'islog',show:'是否记录日志',type:'select',items:isornotOption}
			,{name:'disabled',show:'是否禁用',type:'select',items:isornotOption}
			,{name:'datasourceid',show:'数据源',type:'select',items:dataSourceOption}
			,{name:'main',show:'SQL语句',type:'ace',aceType:'mysql'}
			,{name:'serviceparams',show:'参数列表'}
		]
		,action:[
			{name:'name',show:'名称'}
			,{name:'l10n',show:'描述'}
			,{name:'locktype',show:'锁类型',type:'select',items:lockTypeOption}
			,{name:'isfilter',show:'是否过滤',type:'select',items:isfilterOption}
			,{name:'islog',show:'是否记录日志',type:'select',items:isornotOption}
			,{name:'disabled',show:'是否禁用',type:'select',items:isornotOption}
			,{name:'main',show:'JS语句',type:'ace',aceType:'javascript',height:'300px'}
		]
		,user:[
			{name:'username',show:'用户名'}
			,{name:'userpwd',show:'用户密码'}
		]
		,role:[
			{name:'name',show:'名称'}
			,{name:'l10n',show:'描述'}
		]
		,resource:[
			{name:'name',show:'资源名称'}
			,{name:'version',show:'版本'}
			,{name:'type',show:'链接类型',type:'select',items:sourceTypeOption}
			,{name:'filetype',show:'资源类型',type:'select',items:sourceFileTypeOption}
			,{name:'main',show:'文件内容',type:'ace'}
			,{name:'ordernum',show:'排序'}
		]
	};

	let constUpdateItems = {
		application:[
			{name:'name',disabled:true,show:'应用名称'}
			,{name:'title',show:'应用标题'}
			,{name:'description',show:'应用描述',type:'textarea'}
			,{name:'keywords',show:'应用关键字'}
			,{name:'authurl',show:'授权地址'}
			,{name:'viewport',show:'页面视图'}
			,{name:'before_service',show:'执行服务'}
			,{name:'before_action',show:'执行动作'}
			,{name:'isfilter',show:'是否过滤',type:'select',items:isfilterOption}
			,{name:'islog',show:'是否记录日志',type:'select',items:isornotOption}
			,{name:'debug',show:'是否调试',type:'select',items:isornotOption}
			,{name:'disabled',show:'是否禁用',type:'select',items:isornotOption}
		]
		,service:[
			{name:'name',disabled:true,show:'名称'}
			,{name:'l10n',show:'描述'}
			,{name:'type',show:'类型',type:'select',items:serviceTypeOption}
			,{name:'isfilter',show:'是否过滤',type:'select',items:isfilterOption}
			,{name:'islog',show:'是否记录日志',type:'select',items:isornotOption}
			,{name:'disabled',show:'是否禁用',type:'select',items:isornotOption}
			,{name:'datasourceid',show:'数据源',type:'select',items:dataSourceOption}
			,{name:'main',show:'SQL语句',type:'ace',aceType:'mysql'}
			,{name:'serviceparams',show:'参数列表'}
		]
		,action:[
			{name:'name',disabled:true,show:'名称'}
			,{name:'l10n',show:'描述'}
			,{name:'locktype',show:'锁类型',type:'select',items:lockTypeOption}
			,{name:'isfilter',show:'是否过滤',type:'select',items:isfilterOption}
			,{name:'islog',show:'是否记录日志',type:'select',items:isornotOption}
			,{name:'disabled',show:'是否禁用',type:'select',items:isornotOption}
			,{name:'main',show:'JS语句',type:'ace',aceType:'javascript',height:'300px'}
		]
		,user:[
			{name:'username',disabled:true,show:'用户名'}
			,{name:'userpwd',show:'用户密码'}
		]
		,role:[
			{name:'name',disabled:true,show:'名称'}
			,{name:'l10n',show:'描述'}
		]
		,resource:[
			{name:'name',show:'资源名称'}
			,{name:'version',show:'版本'}
			,{name:'type',show:'链接类型',type:'select',items:sourceTypeOption}
			,{name:'filetype',show:'资源类型',type:'select',items:sourceFileTypeOption}
			,{name:'main',show:'文件内容',type:'ace'}
			,{name:'ordernum',show:'排序'}
		]
	}
	
	let constNavbarChildren = [
		{content:'应用',key:'application'}
		,{content:'服务',key:'service'}
		,{content:'动作',key:'action'}
		,{content:'资源',key:'resource'}
		,{content:'用户',key:'user'}
		,{content:'角色',key:'role'}
	];
	
	let constAppName;
	
	for(let i=0,len=constNavbarChildren.length;i<len;i++){
		if(constNavbarChildren[i].key === query_app){
			constNavbarChildren[i].active = true;
			constAppName = constNavbarChildren[i].content;
		}
		constNavbarChildren[i].href = 'console?app=' 
			+ constNavbarChildren[i].key;
	}
	
	let comController = {
		app:r.createFactory(r.createClass({
			getInitialState:function(){
        return {
					data:null
					,defaultRoleData:null
					,defaultResourceData:null
					,defaultUserRoleData:null
				};
      },
			loadBrowseData:function(){
				let self = this;
				let state = self.state;
				let props = self.props;
				let serviceName = CONST.TABLE_PREFIX + '_' + query_app + '_browse';
				let s = {};
        server.invokeService(serviceName,{id:config.query.id}).then(function(result){
          if(result.length>0){
						s.data = result[0];
						self.setState({data:result[0]});
          }
        });
			},
			loadEditData:function(){
				let self = this;
				let state = self.state;
				let props = self.props;
				let serviceName = CONST.TABLE_PREFIX + '_application_browse_' + config.query.edittype + '_byappid';
				let s = {};
        server.invokeService(serviceName,{id:config.query.id}).then(function(result){
          if(result.length>0){
						s.data = result[0];
						self.setState({data:result[0]});
          }
        });
			},
			loadAuthData:function(){
				let self = this;
				let state = self.state;
				let props = self.props;
				let serviceName2 = CONST.TABLE_PREFIX + '_role_list_byauth';
				let p1 =  {
					whatid:config.query.id
					,whattype:props.app
				};
				server.invokeService(serviceName2,p1).then(function(result){
					if(result.length>0){
						let defaultRoleData = {};
						for(let i=0,len=result.length;i<len;i++){
							let o1 = result[i];
							defaultRoleData[o1.id]  = o1;
						}
						self.setState({defaultRoleData:defaultRoleData});
					}
				});
			},
			loadResourceData:function(){
				let self = this;
				let state = self.state;
				let props = self.props;
				let serviceName2 = CONST.TABLE_PREFIX + '_resource_list_byappid';
				let p1 = {
					appid:config.query.id
				};
				server.invokeService(serviceName2,p1).then(function(result){
					if(result.length>0){
						let defaultResourceData = {};
						for(let i=0,len=result.length;i<len;i++){
							let o1 = result[i];
							defaultResourceData[o1.id]  = o1;
						}
						self.setState({defaultResourceData:defaultResourceData});
					}
				});
			},
			loadUserRoleData:function(){
				let self = this;
				let state = self.state;
				let props = self.props;
				let serviceName2 = CONST.TABLE_PREFIX + '_role_list_byuser';
				let p1 = {
					userid:config.query.id
				};
				server.invokeService(serviceName2,p1).then(function(result){
					if(result.length>0){
						let defaultUserRoleData = {};
						for(let i=0,len=result.length;i<len;i++){
							let o1 = result[i];
							defaultUserRoleData[o1.id]  = o1;
						}
						self.setState({defaultUserRoleData:defaultUserRoleData});
					}
				});
			},
			componentDidMount:function(){
        let self = this;
				let state = self.state;
				let props = self.props;
				if(props.app_fun === 'update' || props.app_fun === 'copy'){
					self.loadBrowseData();
				}else if(props.app_fun === 'auth'){
					self.loadAuthData();
				}else if(props.app_fun === 'resource'){
					self.loadResourceData();
				}else if(props.app_fun === 'user_role'){
					self.loadUserRoleData();
				}else if(props.app_fun === 'edit'){
					self.loadEditData();
				}
      }
			,render:function(){
				let self = this;
				let props = self.props;
				let state = self.state;
				let ret,menu,gridlist;
				let navbarChildren = constNavbarChildren;
				
				menu = components.createBase.apply(components,['list',{}].concat(constNavbarChildren));
				
				if(props.app_fun === 'main' || props.app_fun === 'auth'
						|| props.app_fun === 'resource' || props.app_fun === 'user_role'){
					let title = constAppName + '列表';
					let defaultParams;
					let canSelect = 'radio';
					let headers = constGridHeaders[props.app];
					let operations = constGridOperations[props.app];
					let serviceName = CONST.TABLE_PREFIX + '_' + props.app + '_list';
					let countServiceName = CONST.TABLE_PREFIX + '_' + props.app + '_list_count';
					let defaultSelectedItems;
					if(props.app_fun === 'auth'){
						title = '关联角色';
						serviceName = CONST.TABLE_PREFIX + '_role_list';
						canSelect = true;
						operations = [{name:'关联角色',theme:'primary',onClick:gFunLinkRole}];
						countServiceName = null;
						defaultSelectedItems = state.defaultRoleData;
						headers = constGridHeaders['role'];
					}else if(props.app_fun === 'resource'){
						title = '关联资源';
						serviceName = CONST.TABLE_PREFIX + '_resource_list';
						canSelect = true;
						operations = [{name:'关联资源',theme:'primary',onClick:gFunLinkResource}];
						countServiceName = null;
						defaultSelectedItems = state.defaultResourceData;
						headers = constGridHeaders['resource'];
					}else if(props.app_fun === 'user_role'){
						title = '关联角色';
						serviceName = CONST.TABLE_PREFIX + '_role_list';
						canSelect = true;
						operations = [{name:'关联角色',theme:'primary',onClick:gFunUserRoleResource}];
						countServiceName = null;
						defaultSelectedItems = state.defaultUserRoleData;
						headers = constGridHeaders['role'];
					}
					gridlist = components.createController('gridlist',{
						id:props.app + '_gridlist'
						,serviceName:serviceName
						,defaultParams:defaultParams
						,countServiceName:countServiceName
						,title:title
						,defaultSelectedItems:defaultSelectedItems
						,canSelect:canSelect
						,hasNo:true
						,pageSize:50
						,headers:headers
						,operations:operations
					});
				}else if(props.app_fun === 'insert' || props.app_fun === 'update' || props.app_fun === 'copy'){
					let title = '新增';
					let items = constInsertItems[props.app];
					let actionName = CONST.TABLE_PREFIX + '_' + props.app + '_insert';
					let params = {};
					if(props.app_fun === 'update'){
						title = '修改';
						params.id = config.query.id;
						actionName = CONST.TABLE_PREFIX + '_' + props.app + '_update';
						items = constUpdateItems[props.app];
					}
					if(props.app_fun === 'copy'){
						title = '复制';
						params.copyid = config.query.id;
						actionName = CONST.TABLE_PREFIX + '_' + props.app + '_copy';
						items = constCopyItems[props.app];
					}
					gridlist = components.createController('form',{
						id:props.app + '_gridlist'
						,title:title + constAppName
						,defaultData:state.data
						,items:items
						,onSubmit:function(e){
							e.preventDefault();
							let arr = $(e.target).serializeArray();
							for(let i=0,len=arr.length;i<len;i++){
								let one = arr[i];
								params[one.name] = one.value;
							}
							server.invokeAction(actionName,params).then(function(result){
									alert(result);
									location = config.appname + '?app=' + query_app;
							})['catch'](server.catchFun);
							return false;
						}
					});
				}else if(props.app_fun === 'edit'){
					let title = '编辑';
					let edittype = config.query.edittype;
					let aceType = edittype;
					if(aceType === 'js') aceType ='javascript';
					if(aceType === 'css') aceType ='less';
					let items = [{name:'main',show:edittype,aceType:aceType,type:'ace',height:'500px'}];
					let serviceName = CONST.TABLE_PREFIX + '_' + props.app + '_update_' + edittype;
					let params = {};
					params.id = config.query.id;
					gridlist = components.createController('form',{
						id:props.app + '_gridlist'
						,title:title + constAppName
						,defaultData:state.data
						,items:items
						,onSubmit:function(e){
							e.preventDefault();
							let arr = $(e.target).serializeArray();
							for(let i=0,len=arr.length;i<len;i++){
								let one = arr[i];
								params[one.name] = one.value;
							}
							server.invokeService(serviceName,params).then(function(result){
									alert('修改成功');
									location = config.appname + '?app=' + query_app;
							})['catch'](server.catchFun);
							return false;
						}
					});
				}
				
				ret = components.createBase('container',{className:'full'}
					,components.createBase('grid',{}
						,{xs:2,content:menu}
						,{xs:10,content:gridlist}
					)
				);
				return ret;
			}
		}))
	};
  
  let mycom = {
    main:r.createFactory(r.createClass({
      render:function(){
        let self = this;
        let props = self.props;
        let state = self.state;
        return r.DOM.div({}
					,components.createBase('navbar',{title:config.apptitle})
          ,components.createBase('container',{className:'full'}
						,components.createBase('button',{theme:'primary',type:'a',href:'../clearCache',target:'_blank'},'清空缓存')
						,components.createBase('button',{theme:'info',type:'a',href:'../startCron',target:'_blank'},'开始定时任务')
						,components.createBase('button',{theme:'warning',type:'a',href:'../stopCron',target:'_blank'},'停止定时任务')
						,components.createBase('button',{theme:'danger',type:'a',href:'../loginOut',target:'_self'},'退出')
					)
					,r.DOM.br()
					,comController.app({
            app:query_app
            ,app_fun:query_fun
          })
        );
      }
    }))
  }
  
  let app = {
    init:function(){
      let serviceName = CONST.TABLE_PREFIX + '_datasource_list';
			server.invokeService(serviceName).then(function(result){
				for(let i=0,len=result.length;i<len;i++){
					let one = result[i];
					dataSourceOption.push({value:one.id,name:one.name});
				}
				app.initPage();
			});
    }
    ,initPage:function(){
      rd.render(mycom.main(),$('#body').get(0));
    }
  };
  
  $(function(){
    app.init();
  });
})(vinculum);
